package com

import(
	"github.com/garyburd/redigo/redis"
	"gopkg.in/mgo.v2"
	"github.com/bugfan/logrus"
	"strings"
)
type RedisConf struct{
	Url string 
}
func (s * RedisConf)Ip()string{
	r:=strings.Split(s.IpAndPort(),":")
	if len(r)==2{
		return r[0]
	}
	return ""
}
func (s * RedisConf)Port()string{
	r:=strings.Split(s.IpAndPort(),":")
	if len(r)==2{
		return r[1]
	}
	return ""
}
func (s * RedisConf)Passsword()string{
	r:=strings.Split(s.Url,"@")
	if len(r)<2{
		return ""
	}
	t:=strings.Split(r[0],"//")
	if len(t)<2{
		return ""
	}
	y:=strings.Split(t[1],":")
	if len(y)<2{
		return ""
	}
	return y[1]
}
func (s * RedisConf)Index()string{
	r:=strings.Split(s.Url,"@")
	if len(r)<2{
		return ""
	}
	t:=strings.Split(r[1],"/")
	if len(t)==2{
		return t[1]
	}
	return ""
}
func (s * RedisConf)IpAndPort()string{
	r:=strings.Split(s.Url,"@")
	if len(r)<2{
		return ""
	}
	t:=strings.Split(r[1],"/")
	return t[0]
}
/**************************** redis **************************/
var Redis redis.Conn
func InitRedis(url string)bool{
	opt:=&RedisConf{
		Url: url,
	}
	c, err := redis.Dial("tcp", opt.IpAndPort())
    if err != nil {
		logrus.Error("Connect to redis error", err)
		return false
	}
	_, err = c.Do("auth", opt.Passsword())
	if err != nil {
		logrus.Println("redis set auth:", err)
	}
	_, err = c.Do("select", opt.Index())
	if err != nil {
		logrus.Println("redis select index:", err)
	}
	// 解决真机存储异常 config set stop-writes-on-bgsave-error no
	logrus.Info("redis 连接成功! ")
	Redis=c
	return  true
}

/*************** mongodb ******************/
var MongoDB *mgo.Session
func InitMongodb(url string)bool{
	session,err:= mgo.Dial(url)
    if err!=nil{
    	logrus.Error("connect to mongodb error:",err)
    	return false
	}
	session.SetMode(mgo.Monotonic, true)
	MongoDB=session
	logrus.Info(("mongodb 连接成功! "))
	return true
}